package com.jyh.util;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONException;

public class JavaBeanForMap {
	public static final Logger logger = LoggerFactory.getLogger(JavaBeanForMap.class);
	private static Pattern humpPattern = Pattern.compile("[A-Z]");
	/**
	 * 将javabean实体类转为map类型，然后返回一个map类型的值
	 * 
	 * @param obj
	 * @return
	 */
	public static Map<String, String> beanToMap(Object obj) {
		Map<String, String> params = new HashMap<String, String>(0);
		try {
			PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
			PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
			for (int i = 0; i < descriptors.length; i++) {
				String name = descriptors[i].getName();
				if (!"class".equals(name)) {
					String vault = propertyUtilsBean.getNestedProperty(obj, name) + "";
					if (getMapString(vault)) {
						params.put(name, vault);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return params;
	}

	/**
	 * 将json转化为实体POJO
	 * 
	 * @param jsonStr
	 * @param obj
	 * @return
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	public static <T> Object jsonToObject(String jsonStr, Class<T> obj)
			throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		T t = objectMapper.readValue(jsonStr, obj);
		return t;
	}

	/**
	 * 将json转化为实体POJO
	 * 
	 * @param jsonStr
	 * @param obj
	 * @return
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	public static <T> T JSONToObj(String jsonString, Class<T> pojoCalss) throws IOException {
		net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(jsonString);
		Object pojo = net.sf.json.JSONObject.toBean(jsonObject, pojoCalss);
		return (T) pojo;
	}

	/**
	 * 将实体POJO转化为JSON
	 * 
	 * @param obj
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public static <T> String objectToJson(T obj) throws JSONException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		// Convert object to JSON string
		String jsonStr = "";
		try {
			jsonStr = mapper.writeValueAsString(obj);
		} catch (IOException e) {
			throw e;
		}
		return jsonStr;
	}

	/**
	 * 验证参数是否为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean getMapString(String str) {
		if ("null".equals(str) || "".equals(str) || null == str) {
			str = "false";
		}
		return true;
	}

	public static String camelName(String name) {
		StringBuilder result = new StringBuilder();
		// 快速检查
		if (name == null || name.isEmpty()) {
			// 没必要转换
			return "";
		} else if (!name.contains("_")) {
			// 不含下划线，仅将首字母小写
			return name.substring(0, 1).toLowerCase() + name.substring(1);
		}
		// 用下划线将原始字符串分割
		String camels[] = name.split("_");
		for (String camel : camels) {
			// 跳过原始字符串中开头、结尾的下换线或双重下划线
			if (camel.isEmpty()) {
				continue;
			}
			// 处理真正的驼峰片段
			if (result.length() == 0) {
				// 第一个驼峰片段，全部字母都小写
				result.append(camel.toLowerCase());
			} else {
				// 其他的驼峰片段，首字母大写
				result.append(camel.substring(0, 1).toUpperCase());
				result.append(camel.substring(1).toLowerCase());
			}
		}
		return result.toString();
	}

	/**
	 * 将MAP中key更改驼峰
	 * 
	 * @param map
	 * @return
	 */
	public static Map<String, Object> getCamelNameMap(Map<String, Object> map) {
		Map<String, Object> mapReturn = new HashMap<String, Object>();
		for (String key : map.keySet()) {
			mapReturn.put(camelName(key), map.get(key));
		}

		return mapReturn;
	}
	
	
	/**
	 * 将MAP中key更改驼峰
	 * 
	 * @param map
	 * @return
	 */
	public static Map<String, Object> getCamelNameMap2(Map<String, Object> map) {
		Map<String, Object> mapReturn = new HashMap<String, Object>();
		for (String key : map.keySet()) {
			mapReturn.put(underlineToCamel2(key), map.get(key));
		}

		return mapReturn;
	}
	
	 /**驼峰转下划线*/  
    public static String humpToLine2(String str){  
        Matcher matcher = humpPattern.matcher(str);  
        StringBuffer sb = new StringBuffer();  
        while(matcher.find()){  
            matcher.appendReplacement(sb, "_"+matcher.group(0).toLowerCase());  
        }  
        matcher.appendTail(sb);  
        return sb.toString();  
    } 
    
    /**
     * 下划线格式字符串转换为驼峰格式字符串2
     * 
     * @param param
     * @return
     */
    public static String underlineToCamel2(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        StringBuilder sb = new StringBuilder(param);
        Matcher mc = Pattern.compile("_").matcher(param);
        int i = 0;
        while (mc.find()) {
            int position = mc.end() - (i++);
            sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
        }
        return sb.toString();
    }

    
    
    /**
     * 将JSONObjec对象转换成Map集合
     * @see JSONHelper#reflect(JSONArray)
     * @param json
     * @return
     */
    public static HashMap<String, Object> reflect(net.sf.json.JSONObject json){
        HashMap<String, Object> map = new HashMap<String, Object>();
        Set keys = json.keySet();
        for(Object key : keys){
            Object o = json.get(key);
            if(o instanceof net.sf.json.JSONArray)
                map.put((String) key, reflect((net.sf.json.JSONArray) o));
            else if(o instanceof net.sf.json.JSONObject)
                map.put((String) key, reflect((net.sf.json.JSONObject) o));
            else
                map.put((String) key, o);
        }
        return map;
    }

    /**
     * 将JSONArray对象转换成List集合
     * @see JSONHelper#reflect(JSONObject)
     * @param json
     * @return
     */
    public static Object reflect(net.sf.json.JSONArray json){
        List<Object> list = new ArrayList<Object>();
        for(Object o : json){
            if(o instanceof net.sf.json.JSONArray)
                list.add(reflect((net.sf.json.JSONArray) o));
            else if(o instanceof net.sf.json.JSONObject)
                list.add(reflect((net.sf.json.JSONObject) o));
            else
                list.add(o);
        }
        return list;
    }
}
